package cn.sxt.clinic.service.impl;

import cn.sxt.clinic.mapper.RegistrationDetailMapper;
import cn.sxt.clinic.pojo.Registration;
import cn.sxt.clinic.mapper.RegistrationMapper;
import cn.sxt.clinic.pojo.RegistrationDetail;
import cn.sxt.clinic.service.IRegistrationService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-06-29
 */
@Service
public class RegistrationServiceImpl extends ServiceImpl<RegistrationMapper, Registration> implements IRegistrationService {

    @Autowired
    private RegistrationDetailMapper registrationDetailMapper;

    @Override
    public boolean insertOrUpdate(Registration registration) {
        //1.先将子表基础信息插入到挂号表中，并获取数据库生成的挂号id
        boolean flag = this.saveOrUpdate(registration);

        //2.删除子表明细表中原有的数据
        UpdateWrapper<RegistrationDetail> wrapper = new UpdateWrapper<>();
        wrapper.eq("registration_id",registration.getRegistrationId());
        registrationDetailMapper.delete(wrapper);

        List<RegistrationDetail> registrationDetails = registration.getRegistrationDetails();
        for (RegistrationDetail registrationDetail : registrationDetails) {
            //3.循环子表明细，将获取的挂号id设置给每一个子表明细
            registrationDetail.setRegistrationId(registration.getRegistrationId());

            //循环插入子表明细
            registrationDetailMapper.insert(registrationDetail);
        }

        return flag;
    }
}
